package com.itheima.service.Impl;

import com.alibaba.fastjson.JSON;
import com.itheima.domain.Product;
import com.itheima.mapper.ProductMapper;
import com.itheima.service.ProductService;
import org.apache.dubbo.config.annotation.DubboService;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@DubboService

@Service
public class ProductServiceImpl implements ProductService {
    /**
     * 搜索商品信息
     * @param searchString 搜索条件
     * @return 搜索结果
     */
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private RestHighLevelClient client;







    @Override
    public List<Product> search(String searchString) {
        //List<Product> list = productMapper.search(searchString);
        //return list;
        List<Product> list = null;
        try {
            //2 创建搜索请求对象
            SearchRequest searchRequest=new SearchRequest("j_product");
            //4 创建查询条件构建器对象
            SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();


            //6 设置查询条件
            QueryBuilder queryBuilder= QueryBuilders.matchQuery("title",searchString);

            //5.2 设置高亮三要素
            HighlightBuilder highlightBuilder=new HighlightBuilder()
                    .field("title")
                    .preTags("<font color='red'>")
                    .postTags("</font>");
            //5 添加查询条件
            //5.1 添加查询条件和高亮
            searchSourceBuilder.query(queryBuilder)
                    .highlighter(highlightBuilder)
                    .from(0).size(20);

            //3 添加查询条件构建器对象
            searchRequest.source(searchSourceBuilder);

            //1 开始搜索
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

            //7 处理结果，将查结果封装成List<Product>
            SearchHit[] hits = response.getHits().getHits();
            list = Arrays.stream(hits).map(hit -> {
                        Product product = JSON.parseObject(hit.getSourceAsString(), Product.class);
                        String title = hit.getHighlightFields().get("title").getFragments()[0].string();
                        product.setTitle(title);
                        return product;
                    }

            ).collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;

    }

    /**
     * 添加商品信息
     * @param product 商品对象
     */
    @Override
    public void add(Product product) {
        //1 向MySQL中添加产品信息
        productMapper.add(product);
        //2 向ES中添加产品信息,创建文档
        try {
            //2.2 创建请求对象，指定要保存到的索引库
            IndexRequest indexRequest=new IndexRequest("j_product");
            //2.3 向请求中添加要保存的数据
            indexRequest.id(String.valueOf(product.getId())).source(JSON.toJSONString(product), XContentType.JSON);
            //2.1 开始发送请求，创建文档
            IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
            System.out.println(response.status());  //如果创建成功，结果就是OK
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Product> findAll() {
        return productMapper.findAll();
    }
}
